package com.nangle.managehost.fragmet;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;

import android.support.annotation.Nullable;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.chingteach.chartlibrary.model.Axis;
import com.chingteach.chartlibrary.model.AxisValue;
import com.chingteach.chartlibrary.model.Line;
import com.chingteach.chartlibrary.model.LineChartData;
import com.chingteach.chartlibrary.model.PointValue;
import com.chingteach.chartlibrary.model.ValueShape;
import com.chingteach.chartlibrary.model.Viewport;
import com.chingteach.chartlibrary.view.LineChartView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.nangle.managehost.BaseFargment;
import com.nangle.managehost.R;
import com.nangle.managehost.adapter.MySpinnerAdapter;
import com.nangle.managehost.adapter.PatientAdapter;
import com.nangle.managehost.data.LineChartDummyData;
import com.nangle.managehost.dialog.MyDialog;

import com.nangle.managehost.entity.Patient;

import com.nangle.managehost.manager.PatientManager;
import com.nangle.managehost.view.DragGridView;

import java.util.ArrayList;

import java.util.Hashtable;
import java.util.List;


import static android.graphics.Color.BLACK;

/**
 * 作者：Administrator on 2016/10/18 15:44
 * 描述：
 */

public class PatientFragment extends BaseFargment implements AdapterView.OnItemClickListener, View.OnClickListener,View.OnTouchListener ,GestureDetector.OnGestureListener{
    private DragGridView mGridView;

    private PatientAdapter mAdapter;
    private RelativeLayout warddetail_layout;
    private RelativeLayout detailshow_layout;
    private ImageView showdetail_button;
    private Boolean right_show = false;
    private TextView animation_text;
    private ImageView back;
    private ImageView hide;
    private GestureDetector gestureDetector;
    private int isDetail = 0;
    private static final int FLING_MIN_DISTANCE = 50;
    private static final int FLING_MIN_VELOCITY = 0;
    private ArrayList<String> spinner_list;
    private ImageView imgView;
    private TextView textView;
    private LinearLayout layout;
    private ListView listView;
    private MySpinnerAdapter spinner_adapter;
    private PopupWindow popupWindow;
    private LinearLayout spinnerlayout;
    private TextView tvBedNum,tvPatientName,tvPatientSex,tvPatientGrade;
    int width;
    private ImageView ivqr;
    private List<Patient> mDatas = new ArrayList<>();
    private LineChartView chart;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.wardfragment_view, container, false);

        mGridView = (DragGridView) view.findViewById(R.id.wardview_gridview);
        getData();
        mGridView.setAdapter(mAdapter = new PatientAdapter(getActivity(), mDatas));
        mGridView.setOnItemClickListener(this);
        gestureDetector = new GestureDetector(mActivity, this);
        mGridView.setOnChangeListener(new DragGridView.OnChanageListener(){

            @Override
            public void onChange(int form, int to) {


            }
        });
        mGridView.setOnFinshListener(new DragGridView.OnFinshListener() {
            @Override
            public void onFinsh(int form, int to) {
                Log.e("ssss","form is "+form+"  to is "+ to);
                if(form>=0) {
                    String content = String.format("确认与%d床进行交换操作？", to + 1);
                    showLoginDialog(content, form, to);
                }
            }
        });
        ivqr = (ImageView)view.findViewById(R.id.ivqr);
        warddetail_layout = (RelativeLayout) view.findViewById(R.id.warddetail_rlayout);
        warddetail_layout.setOnTouchListener(this);
        detailshow_layout = (RelativeLayout) view.findViewById(R.id.detailshow_rlayouts);
        detailshow_layout.setOnTouchListener(this);
        showdetail_button = (ImageView) view.findViewById(R.id.detail_show);
        showdetail_button.setOnClickListener(this);
        animation_text = (TextView) view.findViewById(R.id.animation_text);
        back = (ImageView) view.findViewById(R.id.back_bedcard);
        back.setOnClickListener(this);
        hide = (ImageView) view.findViewById(R.id.hide_all);
        hide.setOnClickListener(this);
        spinner_list = new ArrayList<String>();
        spinner_list.add("第一展厅");
        spinner_list.add("4展厅");
        spinner_list.add("第三展厅");
        spinner_adapter = new MySpinnerAdapter(getActivity(), spinner_list);
        textView = (TextView) view.findViewById(R.id.dropdown_text);
        textView.setText(spinner_list.get(0).toString());
        spinnerlayout = (LinearLayout) view.findViewById(R.id.spinnerid);
        // 点击右侧按钮，弹出下拉框
        imgView = (ImageView) view.findViewById(R.id.dropdown_imageview);
        imgView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (spinner_list.size() > 0) {
                    //spinnerlayout.setBackgroundResource(R.drawable.preference_first_item);
                }
                showWindow(spinnerlayout, textView);

            }
        });
        tvBedNum = (TextView) view.findViewById(R.id.tv_bed_num);
        tvPatientGrade = (TextView)view.findViewById(R.id.tv_grade);
        tvPatientName = (TextView)view.findViewById(R.id.name_patient);
        tvPatientSex = (TextView)view.findViewById(R.id.sex_tv);
        chart = (LineChartView)view.findViewById(R.id.chart);
//        setDae();
        return view;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        return gestureDetector.onTouchEvent(event);
    }

    private void changeBed(int form,int to){
        Patient formTemp = mDatas.get(form);
        Patient toTemp = mDatas.get(to);
        int formBedNum = formTemp.getBed();
        int toBedNum = toTemp.getBed();
        formTemp.setBed(toBedNum);
        toTemp.setBed(formBedNum);

        mDatas.set(form,toTemp);
        mDatas.set(to, formTemp);
        PatientManager.getInstance(mActivity).updateStatus(formTemp.getId(),toBedNum);
        PatientManager.getInstance(mActivity).updateStatus(toTemp.getId(),formBedNum);
        mAdapter.notifyDataSetChanged();
        Toast.makeText(mActivity,"换床成功",Toast.LENGTH_LONG).show();
    }

    private void showLoginDialog(String content,final int form,final int to) {
        View view = mActivity.getLayoutInflater().inflate(R.layout.dialog_layout, null);
        final TextView tvContent = (TextView)view.findViewById(R.id.tv_dialog_content);
        tvContent.setText(content);
        final TextView btnYes = (TextView) view.findViewById(R.id.f_quchecbutton_btn_queding);
        final TextView btlNo = (TextView) view.findViewById(R.id.f_quchecbutton_btn_quxiao);
        final MyDialog builder = new MyDialog(mActivity,0,0,view,R.style.DialogTheme);

        builder.setCancelable(false);
        builder.show();
        //设置对话框显示的View
        //点击确定是的监听
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                changeBed(form,to);
                builder.cancel();
            }
        });


        btlNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.detail_show:
                showDetail();
                break;
            case R.id.back_bedcard:
                hideRight();
                break;
            case R.id.hide_all:
                hideAll();
                break;
        }

    }
    private void hideRight(){
        float curTranslationX = warddetail_layout.getTranslationX();
        ObjectAnimator animator = ObjectAnimator.ofFloat(warddetail_layout, "translationX", curTranslationX, 0f);
        ObjectAnimator animator_grid = ObjectAnimator.ofFloat(mGridView, "translationX", curTranslationX, 0f);
        animator.setDuration(500);
        animator_grid.setDuration(500);
        AnimatorSet animSet = new AnimatorSet();
        animSet.setDuration(500);
        animSet.setInterpolator(new LinearInterpolator());
        //两个动画同时执行
        animSet.playTogether(animator, animator_grid);
        // animSet.play();
        animSet.start();
        isDetail = 0;
        right_show = false;
    }
    private void showDetail(){
        float curTranslationX_detail = warddetail_layout.getTranslationX();
        ObjectAnimator animator_detail = ObjectAnimator.ofFloat(warddetail_layout, "translationX", curTranslationX_detail, -950f);
        ObjectAnimator animator_griddetial = ObjectAnimator.ofFloat(mGridView, "translationX", curTranslationX_detail, -950f);
        ObjectAnimator animator_patient = ObjectAnimator.ofFloat(detailshow_layout, "translationX", curTranslationX_detail, -950f);
        animator_detail.setDuration(500);
        animator_griddetial.setDuration(500);
        animator_patient.setDuration(500);
        AnimatorSet animSet_detail = new AnimatorSet();
        animSet_detail.setDuration(500);
        animSet_detail.setInterpolator(new LinearInterpolator());
        //两个动画同时执行
        animSet_detail.playTogether(animator_detail, animator_griddetial, animator_patient);
        // animSet.play();
        animSet_detail.start();
        showdetail_button.setVisibility(View.GONE);
        back.setVisibility(View.INVISIBLE);
        back.setClickable(false);
        hide.setImageResource(R.drawable.back_g);
        isDetail = 2;
    }
    private void hideAll(){
        float curTranslationXhide = warddetail_layout.getTranslationX();
        ObjectAnimator animator_detail = ObjectAnimator.ofFloat(warddetail_layout, "translationX", curTranslationXhide, 0f);
        ObjectAnimator animator_griddetial = ObjectAnimator.ofFloat(mGridView, "translationX", curTranslationXhide, 0f);
        ObjectAnimator animator_patient = ObjectAnimator.ofFloat(detailshow_layout, "translationX", curTranslationXhide, 0f);
        animator_detail.setDuration(500);
        animator_griddetial.setDuration(500);
        animator_patient.setDuration(500);
        AnimatorSet animSet_detailhide = new AnimatorSet();
        animSet_detailhide.setDuration(500);
        animSet_detailhide.setInterpolator(new LinearInterpolator());
        //两个动画同时执行
        animSet_detailhide.playTogether(animator_detail, animator_griddetial, animator_patient);
        // animSet.play();
        animSet_detailhide.start();
        showdetail_button.setVisibility(View.VISIBLE);
        back.setVisibility(View.VISIBLE);
        back.setClickable(true);
        right_show = false;
        isDetail = 0;
    }
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if(!mDatas.get(i).getName().equals("")) {
            setDetailContent(mDatas.get(i));
            if (!right_show) {
                setDetailContent(mDatas.get(i));
                float curTranslationX = warddetail_layout.getTranslationX();
                ObjectAnimator animator = ObjectAnimator.ofFloat(warddetail_layout, "translationX", curTranslationX, -550f);
                ObjectAnimator animator_grid = ObjectAnimator.ofFloat(mGridView, "translationX", curTranslationX, -550f);
                animator.setDuration(500);
                animator_grid.setDuration(500);
                AnimatorSet animSet = new AnimatorSet();
                animSet.setDuration(500);
                animSet.setInterpolator(new LinearInterpolator());
                //两个动画同时执行
                animSet.playTogether(animator, animator_grid);
                // animSet.play();
                animSet.start();
                // animator.start();
                //   anim.start();
                right_show = true;
                isDetail = 1;
                back.setImageResource(R.drawable.back_g);

            }
        }
    }

    private void setDetailContent(Patient patient){
        tvPatientName.setText(patient.getName());
        Bitmap bitmap;
        try {
            bitmap = createQRCode(patient.getName(),120);
            if (bitmap != null) {
                ivqr.setImageBitmap(bitmap);
            }
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        tvBedNum.setText(""+patient.getBed());
        if(patient.getSex()==0){
            tvPatientSex.setText("女");
        }else{
            tvPatientSex.setText("男");
        }
        if(patient.getNursingGrade()==1){
            tvPatientGrade.setText("Ⅰ级护理");
            tvPatientGrade.setTextColor(getResources().getColor(R.color.red));

        }else if(patient.getNursingGrade()==2){
            tvPatientGrade.setText("Ⅱ级护理");
            tvPatientGrade.setTextColor(getResources().getColor(R.color.yellow));

        }else if(patient.getNursingGrade() == 3){
            tvPatientGrade.setText("Ⅲ级护理");
            tvPatientGrade.setTextColor(getResources().getColor(R.color.blue));

        }else {
            tvPatientGrade.setText("特级护理");
            tvPatientGrade.setTextColor(getResources().getColor(R.color.dark_red));

        }
        showLineChart();
    }



    /*
    展示
     */
    public void showWindow(View position, final TextView txt) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.myspinner_dropdown, null);
        spinner_adapter = new MySpinnerAdapter(getActivity(), spinner_list);
        listView = (ListView) view.findViewById(R.id.dropdown_listView);
        listView.setAdapter(spinner_adapter);
        popupWindow = new PopupWindow(position);
        // 设置弹框的宽度为布局文件的宽
        popupWindow.setWidth(spinnerlayout.getWidth());
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置一个透明的背景，不然无法实现点击弹框外，弹框消失
        // popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置点击弹框外部，弹框消失
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setContentView(view);
        // 设置弹框出现的位置，在v的正下方横轴偏移textview的宽度，为了对齐~纵轴不偏移
        popupWindow.showAsDropDown(position, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                //spinnerlayout.setBackgroundResource(R.drawable.preference_single_item);
            }
        });
        // listView的item点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                txt.setText(spinner_list.get(arg2));// 设置所选的item作为下拉框的标题
                // 弹框消失
                popupWindow.dismiss();
                popupWindow = null;
            }
        });

    }

    private void getData(){
       mDatas =  PatientManager.getInstance(mActivity).getPaitentList();
    }


    @Override
    public boolean onDown(MotionEvent e) {

        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX()-e2.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            // Fling left
            Log.e("sssss","向左手势向左手势向左手势向左手势向左手势");


            if(isDetail == 1){
                showDetail();
            }
        } else if (e2.getX()-e1.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            // Fling right
            Log.e("sssss","向右手势向右手势向右手势向右手势向右手势");
            if(isDetail == 1){
                hideRight();
            }else if(isDetail == 2){
                hideAll();
            }
        }
        return false;
    }
    public static Bitmap createQRCode(String str, int widthAndHeight)throws WriterException {

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix matrix = new MultiFormatWriter().encode(str,
                BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight,hints);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = BLACK;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
    private List<Line> linesList;
    private LineChartData lineChartData;
    /**
     * 画折线图
     * @param points 图表上的点
     */
    private void DrawChart(final List<PointValue> points) {
        linesList = new ArrayList<>();
        Viewport port = initViewPort(42,35,0,24);
        //初始化坐标轴
        Axis axisY = new Axis();
        Axis axisX = new Axis();
        Line line = new Line(points);
//        line.setPointColor(Color.parseColor("#123456"));
//        设置线的颜色,设置线的粗细
        line.setColor(Color.GRAY).setPointRadius(3);
        //设置线上点的形状,设置点的大小
        line.setShape(ValueShape.CIRCLE).setPointRadius(4);
        //设置是否在点上显示标注
        line.setHasLabels(false);
        //设置曲线是否平滑，即是曲线还是折线
        line.setCubic(false);
        linesList.add(line);
        lineChartData = initDatas(linesList);
        lineChartData.setValueLabelBackgroundEnabled(false);
        //设置标注中字体的颜色
        lineChartData.setValueLabelsTextColor(Color.parseColor("#93b9df"));
        //设置隐藏X轴 默认: true
        axisX.setHasSeparationLine(false).setTextColor(Color.parseColor("#4e4e4e"));
        //设置隐藏Y轴 默认: true
        axisY.setHasSeparationLine(false).setTextColor(Color.parseColor("#4e4e4e"));

//        //设置坐标轴的标注
//        List<AxisValue> axisXValues = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            axisXValues.add(new AxisValue(i*10).setLabel((i*10)+""));
//        }
//        axisX.setValues(axisXValues);
//
//        List<AxisValue> axisYValues = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            axisYValues.add(new AxisValue(i*10).setLabel((i*10)+""));
//        }
//        axisY.setValues(axisYValues);
        //设置根据坐标轴上的标注画相应的参考线的方法[原hellocharts就有的]
        //默认：false
        axisX.setHasLines(true);
        axisY.setHasLines(true);
        //还可以设置参考线的颜色

        //将设置好的坐标轴添加上
        lineChartData.setAxisXBottom(axisX);
        lineChartData.setAxisYLeft(axisY);
        //给折线图添加线的集合
        chart.setLineChartData(lineChartData);
        chart.setCurrentViewport(port);
        chart.setMaximumViewport(port);
        //折线图横纵轴坐标是否按照所给折线数据进行收缩，默认：true
        chart.setViewportCalculationEnabled(false);
    }
    //初始化图表
    private LineChartData initDatas(List<Line> lines) {
        LineChartData data = new LineChartData(lines);
        return data;
    }
    private Viewport initViewPort(float top, float bottom, float left, float right) {
        Viewport port = new Viewport();
        port.top = top;
        port.bottom = bottom;
        port.left = left;
        port.right = right;
        return port;
    }
    private void showLineChart() {
        //给折线图添加数据
        Viewport port = initViewPort(42,35,0,24);
        //是否可滚动
        chart.setScrollEnabled(false);
        chart.setCurrentViewport(port);
        chart.setMaximumViewport(port);
        //是否这线可触摸，显示值
        chart.setValueTouchEnabled(false);
        chart.setFocusableInTouchMode(false);
        chart.setViewportCalculationEnabled(false);
        List<PointValue> firstChart = LineChartDummyData.getFirstChart();
        DrawChart(firstChart);
    }


}
